package org.nativejpa.mapping;

import org.apache.commons.lang.ObjectUtils;

import javax.persistence.PersistenceException;
import java.lang.reflect.Field;

/**
 * \@Column field
 *
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 * @create May 2, 2008 2:16:58 PM
 */
public class ColumnMetadata {
    private String name; // column name
    private Field field; // column mapped field

    private Class<?> defineClass;

    private boolean isPK = false;

    private boolean isVersion = false;

    public ColumnMetadata() {
    }

    public String getName() {
        return name;
    }

    protected Field getField() {
        return field;
    }

    public boolean isPK() {
        return isPK;
    }

    public boolean isJoinColumn() {
        return false;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setField(Field field) {
        this.field = field;
        this.field.setAccessible(true);
    }

    public void setPK(boolean PK) {
        isPK = PK;
    }

    public boolean isVersion() {
        return isVersion;
    }

    public void setVersion(boolean version) {
        isVersion = version;
    }

    public Class<?> getDefineClass() {
        return defineClass;
    }

    public void setDefineClass(Class<?> defineClass) {
        this.defineClass = defineClass;
    }

    public String getFieldName(){
        return getField().getName();
    }

    public Class<?> getFieldType(){
        return getField().getType();
    }

    public Object getFieldValue(Object entity){
        try {
            return getField().get(entity);
        }
        catch (IllegalAccessException e) {
            throw new PersistenceException("Failed to get Column " + name + " value with entity: " + entity, e);
        }
    }

    public void setFieldValue(Object entity, Object value) {        
        try {
            getField().set(entity, value);
        }
        catch (IllegalAccessException e) {
            throw new PersistenceException("Failed to set Column " + name + " value with entity: " + entity, e);
        }
    }
}
